import { db, novel, source } from 'novel-parser'
import { ipcMain } from 'electron'
import { CALLBACK,
  DOWNLOAD_NOVEL,
  SOURCES_LIST,
  ADD_SOURCES,
  REMOVE_SOURCES,
  GET_SOURCE,
  NOVEL_LIST,
  ADD_NOVEL,
  REMOVE_NOVEL,
  GET_NOVEL,
  UPDATE_NOVEL,
  GET_NOVEL_CHAPTER,
  CHANG_NOVEL_SOURCE,
  UPDATE_SOURCE,
  BATCH_ADD_SOURCES
} from 'novel-parser/servies/channel'
import { formatError, getNovelChapter } from './service'

async function request (url, callback) {
  ipcMain.on(url, (event, data) => {
    callback(data).then(res => {
      event.sender.send(url + CALLBACK, { code: 200, data: res })
    }).catch(e => {
      event.sender.send(url + CALLBACK, formatError(e))
    })
  })
}

request(NOVEL_LIST, novel[NOVEL_LIST])

request(ADD_NOVEL, novel[ADD_NOVEL])

request(REMOVE_NOVEL, novel[REMOVE_NOVEL])

request(GET_NOVEL, novel[GET_NOVEL])

request(DOWNLOAD_NOVEL, novel[DOWNLOAD_NOVEL])

request(UPDATE_NOVEL, novel[UPDATE_NOVEL])

request(CHANG_NOVEL_SOURCE, source[CHANG_NOVEL_SOURCE])

request(UPDATE_SOURCE, source[UPDATE_SOURCE])

request(BATCH_ADD_SOURCES, source[BATCH_ADD_SOURCES])

request(SOURCES_LIST, source[SOURCES_LIST])

request(ADD_SOURCES, source[ADD_SOURCES])

request(REMOVE_SOURCES, source[REMOVE_SOURCES])

request(GET_SOURCE, source[GET_SOURCE])

ipcMain.on(GET_NOVEL_CHAPTER, async (event, arg) => {
  const { novelId, chapterId, refresh } = arg
  try {
    const novel = await db.novels.findOne({ _id: novelId })
    let result = await getNovelChapter(novel, chapterId, refresh)
    const chapterIndex = novel.chapters.findIndex(x => x.chapterUrl === chapterId)
    const chapters = novel.chapters
    event.sender.send(GET_NOVEL_CHAPTER + CALLBACK, { code: 200,
      data: {
        chapterList: [
          { title: 'Prev', id: chapters[chapterIndex - 1] ? chapters[chapterIndex - 1].chapterUrl : null },
          { title: 'Index', id: novelId },
          { title: 'Next', id: chapters[chapterIndex + 1] ? chapters[chapterIndex + 1].chapterUrl : null }
        ],
        html: result
      } })
  } catch (e) {
    event.sender.send(GET_NOVEL_CHAPTER + CALLBACK, formatError(e))
  }
})
